package com.ltu.service.impl;

import java.util.Date;
import java.util.List;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Objects;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.config.shiro.ShiroUserService;
import com.ltu.config.shiro.ShiroUtil;
import com.ltu.config.shiro.dto.LoginReq;
import com.ltu.config.shiro.dto.SmsCodeLoginReq;
import com.ltu.constant.CommonConstant;
import com.ltu.domain.mp_entity.AccountEntity;
import com.ltu.domain.mp_entity.Role;
import com.ltu.domain.mp_entity.UserEntity;
import com.ltu.domain.mp_entity.customize.CompanyEntity;
import com.ltu.domain.mp_entity.customize.SessionInfoEntity;
import com.ltu.mapper.UserMapper;
import com.ltu.model.request.base.BaseIdReq;
import com.ltu.model.request.smscode.VerifySmsCodeReq;
import com.ltu.model.request.user.UpdateUserInfoReq;
import com.ltu.model.request.user.UserForgotPassword;
import com.ltu.model.request.user.UserResetPasswordReq;
import com.ltu.model.request.user.UserUpdateReq;
import com.ltu.model.request.user.WxMaLoginReq;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.myannotation.MyReidsCache;
import com.ltu.service.AccountService;
import com.ltu.service.RoleService;
import com.ltu.service.UserService;
import com.ltu.service.VerifySmsCodeService;
import com.ltu.service.customize.CompanyService;
import com.ltu.service.customize.SessionInfoService;
import com.ltu.util.BeanMapper;
import com.ltu.util.common.IdsStrToListUtils;
import com.ltu.util.common.StrUtils;
import com.ltu.util.datetime.DateUtils;
import com.ltu.util.exception.ApiException;
import com.ltu.util.redis.RedisKeyManager;
import com.ltu.util.redis.RedistUtil;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ArrayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * <p>
 * 服务实现类
 * </p>
 * @since 2020-08-15
 */
@Order(199)
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
	private final AccountService accountDaoImpl;
	private final ShiroUserService shiroUserService;
	private final RoleService roleService;
	private final VerifySmsCodeService verifySmsCodeService;
	private final WxMaService wxMaService;
    private final RedistUtil redistUtil;
	private final AiContextManager aiContextManager;
	private final SessionInfoService sessionInfoService;
    
    //单个小程序无需配置
//	private final  CompanyEntity  wxMaMiniAppCfg;

	

	@Autowired
	Environment environment;
	/**
	 * 用户登陆
	 * 
	 * @param userLoginReq
	 * @return
	 */
	public CodeDataResp<UserEntity> login(LoginReq userLoginReq) {
		QueryWrapper<UserEntity> condition = new QueryWrapper<>();
		condition.eq("open_id", userLoginReq.getUsername())
				 .eq("role_type", userLoginReq.getRoleType());
		
		UserEntity userEntity =super.getOne(condition);
		if (userEntity == null) {
			return CodeDataResp.valueOfFailed("用户不存在");
		}
		if (!userLoginReq.getPassword().equals(userEntity.getPassword())) {
			return CodeDataResp.valueOfFailed("用户名或密码错误");
		}
		if (userEntity.getStatus() != 1) {
			return CodeDataResp.valueOfFailed("用户被禁用");
		}
		// 初步验证成功
		String token = shiroUserService.userLoginGetToken(userLoginReq, CommonConstant.LOGIN_TYPE_FRONT,
				userLoginReq.getRoleType());
		userEntity.setLoginCount(userEntity.getLoginCount() + 1);
		userEntity.setLastLoginTime(DateUtils.currentSecs().intValue());
		userEntity.setLoginToken(token);
		super.updateById(userEntity);
		return CodeDataResp.valueOfSuccess(userEntity);
	}

	/**
	 * 20220505 若尘
	 * 商户登陆
	 * @param userLoginReq
	 * @return
	 */
	public CodeDataResp<AccountEntity> loginByAccount(LoginReq userLoginReq) {
		
		LoginReq loginReq = new LoginReq();
		loginReq.setUsername(userLoginReq.getUsername());
		loginReq.setPassword(userLoginReq.getPassword());
		loginReq.setType(CommonConstant.LOGIN_TYPE_BACKSTAGE);
		loginReq.setRoleType(CommonConstant.USER_FRONT_TYPE_INTERNAL);
	
		// 初步验证成功
		String token = shiroUserService.userLoginGetToken(loginReq, CommonConstant.LOGIN_TYPE_BACKSTAGE,
				CommonConstant.USER_FRONT_TYPE_INTERNAL);
		AccountEntity accountEntity = accountDaoImpl.getById(ShiroUtil.getPrincipalUserId());
		accountEntity.setLoginCount(accountEntity.getLoginCount() + 1);
		accountEntity.setLastLoginTime(new Date());
		accountEntity.setLoginToken(token);
		accountDaoImpl.updateById(accountEntity);
		
		
		return CodeDataResp.valueOfSuccess(accountEntity);
	}
	

	/**
	 * 短信验证码登陆
	 * @param userLoginReq
	 * @return
	 */
	public CodeDataResp loginBySmsCode(SmsCodeLoginReq userLoginReq) {
		VerifySmsCodeReq verifySmsCodeReq = new VerifySmsCodeReq();
		verifySmsCodeReq.setSmsCode(userLoginReq.getSmsCode());
		verifySmsCodeReq.setUserPhone(userLoginReq.getUsername());
		if (!verifySmsCodeService.verifySmsCode(verifySmsCodeReq) && !Objects.equal(userLoginReq.getSmsCode(), CommonConstant.DEFAULT_SMS_VERIFY_CODE))
			return CodeDataResp.valueOfFailed("短信验证码错误");

		UserEntity userEntity = getUserByPhone(userLoginReq.getUsername(),userLoginReq.getRoleType());
		if (userEntity == null) {
			String openId="";
			if(StringUtils.isNotBlank(userLoginReq.getWxCode())) {
				WxMaJscode2SessionResult session = null;
				try {
					session = wxMaService.getUserService().getSessionInfo(userLoginReq.getWxCode());
				} catch (WxErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				log.info("微信用户的 openId:{}", session.getOpenid());
				openId = session.getOpenid();
			}
			userEntity=new UserEntity();
			userEntity.setOpenId(openId);
			userEntity.setUserType(1);
			userEntity.setNickName(userLoginReq.getNickName());
			userEntity.setHeadPhoto(userLoginReq.getHeadPhoto());
			userEntity.setPassword("123456");
			userEntity.setUserPhone(verifySmsCodeReq.getUserPhone());
			userEntity.setLoginCount(0);
			userEntity.setStatus((byte) 1);
			userEntity.setRoleType(userLoginReq.getRoleType().byteValue());
			userEntity.setCreateTime(new Date());
			String code = StrUtils.getCode("0","U", new Date());
			userEntity.setCode(code);
			JSONObject param = new JSONObject();
			param.put("code", code);
//			String  returnPath=QRCodeUtil.getQrCodePath(QRCodeTypeEnum.UserQrcode,param);
//			userEntity.setQrCodePath(returnPath);
			super.save(userEntity);
		}else {
			if(userEntity.getStatus()==(byte)0)
				throw new ApiException("用户已冻结，请联系客服");
			
			if(StringUtils.isBlank(userEntity.getOpenId()) && StringUtils.isNotBlank( userLoginReq.getWxCode())) {
			
					WxMaJscode2SessionResult session = null;
					try {
						session = wxMaService.getUserService().getSessionInfo(userLoginReq.getWxCode());
					} catch (WxErrorException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					log.info("微信用户的 openId:{}", session.getOpenid());
					String	openId = session.getOpenid();
					userEntity.setOpenId(openId);
					
				}
			}
			LoginReq loginReq = new LoginReq();
			loginReq.setUsername(userEntity.getUserPhone());
			loginReq.setPassword(userEntity.getPassword());
			loginReq.setType(1);
			loginReq.setRoleType(userLoginReq.getRoleType());
			// 初步验证成功
			String token = shiroUserService.userLoginGetToken(loginReq, CommonConstant.LOGIN_TYPE_FRONT,
					CommonConstant.USER_FRONT_TYPE_NORMAL);
			userEntity.setLoginCount(userEntity.getLoginCount() + 1);
			userEntity.setLastLoginTime(DateUtils.currentSecs().intValue());
			userEntity.setLoginToken(token);
			this.updateById(userEntity);
			return CodeDataResp.valueOfSuccess(userEntity);
			
		
	}


	/**
	 * 注销登录
	 * 
	 * @return
	 */
	public CodeDataResp logout() {
		shiroUserService.userLogout();
		return CodeDataResp.valueOfSuccess("注销成功");
	}

	/**
	 * 重置密码
	 * 
	 * @param req
	 * @return
	 */
	public CodeDataResp resetPassword(UserResetPasswordReq req) {
		UserEntity userEntity = super.getById(req.getUserId());
		if (userEntity == null)
			return CodeDataResp.valueOfErrorNoRecord();
		if (!userEntity.getPassword().equals(req.getOldPassword()))
			return CodeDataResp.valueOfFailed("原密码输入错误");
		userEntity.setPassword(req.getNewPassword());
		super.updateById(userEntity);
		return CodeDataResp.valueOfSuccessEmptyData();
	}

	/**
	 * 忘记密码
	 * 
	 * @param req
	 * @return
	 */
	public CodeDataResp forgotPassword(UserForgotPassword req) {
		VerifySmsCodeReq verifySmsCodeReq = new VerifySmsCodeReq();
		verifySmsCodeReq.setSmsCode(req.getSmsCode());
		verifySmsCodeReq.setUserPhone(req.getUserPhone());
		if (!verifySmsCodeService.verifySmsCode(verifySmsCodeReq))
			return CodeDataResp.valueOfFailed("短信验证码错误");
		
		UserEntity userEntity = getUserByPhone(req.getUserPhone(),CommonConstant.USER_FRONT_TYPE_INTERNAL);
		if (userEntity == null) {
			return CodeDataResp.valueOfErrorNoRecord();
		}
		userEntity.setPassword(req.getPassword());
		this.updateById(userEntity);

		LoginReq loginReq = new LoginReq();
		loginReq.setUsername(userEntity.getUserPhone());
		loginReq.setPassword(userEntity.getPassword());
		return login(loginReq);
	}

	/**
	 * 获取用户详细信息
	 * 
	 * @param baseIdReq
	 * @return
	 */
	public CodeDataResp getUserInfo(BaseIdReq baseIdReq) {
	 UserEntity u=	super.getById(baseIdReq.getId());
//	 if(StringUtils.isNotBlank( u.getHeadPhoto()) &&  !StringUtils.contains(u.getHeadPhoto(), "http")) {
//			String pathStr = environment.getProperty("server.servlet.context-path");
//			pathStr = pathStr.length()>1?pathStr.concat("/"):pathStr;
////			u.setHeadPhoto( localUrl.concat( ":" + environment.getProperty("server.port")).concat(pathStr).concat(u.getHeadPhoto()));
//			u.setHeadPhoto( localUrl.concat(pathStr).concat(u.getHeadPhoto()));
//	 }
	
		return CodeDataResp.valueOfSuccess(u);
	}

	/**
	 * 更新用户信息
	 * 
	 * @param userReq
	 * @return
	 */
	public CodeDataResp updateUserInfo(UpdateUserInfoReq userReq) {
		UserEntity userEntity = super.getById(userReq.getUserId());
		BeanMapper.copy(userReq, userEntity);
		super.updateById(userEntity);
		return CodeDataResp.valueOfSuccess(userEntity);
	}



	/**
	 * MP-获取用户完整信息
	 * 
	 * @param baseIdReq
	 * @return
	 */
	public CodeDataResp getDetail(BaseIdReq baseIdReq) {
		return getUserInfo(baseIdReq);
	}

	/**
	 * MP-保存或修改用户信息
	 * 
	 * @param req
	 * @return
	 */
	public CodeDataResp saveOrUpdate(UserUpdateReq req) {
		// 将角色id排序
		if (!StrUtils.isTrimNull(req.getRoleIds())) {
			req.setRoleIds(sortRoleIds(req.getRoleIds()));
			req.setRoleNames(getRoleNames(req.getRoleIds()));
		}

		UserEntity userEntity;
		if (StrUtils.isTrimNull(req.getUserId())) {
			// 新增
			userEntity = new UserEntity();
			BeanMapper.copy(req, userEntity);
//            user.setId(UUIDGenerator.getUUID())
			userEntity.setCreateTime(new Date());
			// 设置权限等级
			super.save(userEntity);
		} else {
			// 保存
			userEntity = super.getById(req.getUserId());
			if (userEntity == null)
				return CodeDataResp.valueOfErrorNoRecord();
			BeanMapper.copy(req, userEntity);
			// 设置权限等级
			super.updateById(userEntity);
		}
		return CodeDataResp.valueOfSuccess(userEntity);
	}

	/**
	 * 通过手机号获取用户信息
	 * 
	 * @param userPhone
	 * @return
	 */
	public UserEntity getUserByPhone(String userPhone,Integer roleType) {
		if (StrUtils.isTrimNull(userPhone))
			return null;
		QueryWrapper<UserEntity> condition = new QueryWrapper<UserEntity>();
		condition.eq("user_phone", userPhone).eq("role_type", roleType).last("limit 1");
		return this.getOne(condition);
	}

	/**
	 * 获取最高权限值
	 * 
	 * @param roleIds
	 * @return
	 */
	private Integer getAuthorityLevel(String roleIds) {
		Integer result = 3;
		if (StrUtils.isTrimNull(roleIds))
			return result;
		QueryWrapper<Role> condition = new QueryWrapper<>();
		condition.in("id", roleIds);
		List<Role> roleList = roleService.list(condition);
		if (ArrayUtil.isEmpty(roleList))
			return result;
		for (Role role : roleList) {
			if (role.getAuthorityLevel() < result)
				result = role.getAuthorityLevel();
		}
		return result;
	}

	/**
	 * 将角色id按等级排序
	 * 
	 * @param roleIds
	 * @return
	 */
	private String sortRoleIds(String roleIds) {
		// 无角色
		if (StrUtils.isTrimNull(roleIds))
			return null;
		List<String> idList = IdsStrToListUtils.getStringList(roleIds);
		// 只有一个角色，无需排序
		if (idList.size() < 2)
			return roleIds;
		// 准备排序
		QueryWrapper<Role> condition = new QueryWrapper<>();
		condition.in("id", roleIds);
		condition.last("order by authority_level asc");
		List<Role> roleList = roleService.list(condition);
		String result = "";
		for (Role role : roleList) {
			result += role.getId() + ",";
		}
		return StrUtils.removeLastChar(result);
	}

	/**
	 * 根据角色id获取角色名称
	 * 
	 * @param roleIds
	 * @return
	 */
	private String getRoleNames(String roleIds) {
		// 无角色
		if (StrUtils.isTrimNull(roleIds))
			return null;
		List<String> idList = IdsStrToListUtils.getStringList(roleIds);
		String result = "";
		for (String rId : idList) {
			Role role = roleService.getById(rId);
			result += role.getRoleName() + ",";
		}
		return StrUtils.removeLastChar(result);
	}


	@Override
	public void editUserPhone(Integer userId, String phone) {
		UserEntity userEntity = super.getById(userId);
		userEntity.setUserPhone(phone);
		super.updateById(userEntity);

	}
	/**
	 * 通过手机号获取用户信息
	 * 
	 * @param userPhone
	 * @return
	 */
	public UserEntity getUserByOpenId(String openId) {
		if (StrUtils.isTrimNull(openId))
			return null;
		QueryWrapper<UserEntity> condition = new QueryWrapper<>();
		condition.eq("open_id", openId);
		return super.getOne(condition);
	}
	/**
	 * 通过手机号获取用户信息
	 * 
	 * @param userPhone
	 * @return
	 */
	@Override
	@MyReidsCache(enable = true,expireTime = 7200 ,key = RedisKeyManager.RootKey+RedisKeyManager.Splitter+"UserUnionid"+RedisKeyManager.Splitter,fieldKey = "#unionid")
	public UserEntity getUserByUnionid(String unionid,Integer roleType,String companyCode) {
		if (StrUtils.isTrimNull(unionid))
			return null;
		QueryWrapper<UserEntity> condition = new QueryWrapper<>();
		condition.eq("unionid", unionid)
		.eq("company_code",companyCode)
		.eq("role_type", roleType)
		.last("limit 1");
		return super.getOne(condition);
	}
	
	@Override
	@MyReidsCache(compelUpdate = true, enable = true,expireTime = 7200 ,key = RedisKeyManager.RootKey+RedisKeyManager.Splitter+"UserUnionid"+RedisKeyManager.Splitter,fieldKey = "#unionid")
	public UserEntity refreshUserByUnionid(String unionid,Integer roleType,String companyCode) {
		return  getUserByUnionid(unionid,roleType,companyCode);
	}
	/**
	 * 从redis获取用户ID
	 * @param userPhone
	 * @return
	 */
	@Override
	@MyReidsCache(enable = true,expireTime = 7200 ,key = RedisKeyManager.RootKey+RedisKeyManager.Splitter+"User"+RedisKeyManager.Splitter,fieldKey = "#id")
	public UserEntity getUserById(String id) {
		return this.getById(id);
	}
	
	
	/**
	 * 获取微信openId
	 */
	@Override
	public void getWxUserOpendId(UserEntity sysUser, String wxCode) {
		if (StringUtils.isBlank(wxCode))
			return;
		
		try {
			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxCode);
			log.info("微信用户的 openId:{}", session.getOpenid());
			UserEntity oldUser =	 getUserByOpenId(session.getOpenid());
			if(oldUser!=null && !oldUser.getId().equals(sysUser.getId())) {
				oldUser.setOpenId("").setUpdateTime(new Date());
				this.updateById(oldUser);
			}
			sysUser.setOpenId(session.getOpenid());
			this.updateById(sysUser);
		} catch (WxErrorException e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}
	}

	/**
	 *小程序授权登录 获取openId和用户手机号码
	 * @param userLoginReq
	 * @return
	 * @throws WxErrorException 
	 */
	@Override
	public CodeDataResp<UserEntity> loginByWx(WxMaLoginReq userLoginReq) throws WxErrorException {
		if (StringUtils.isBlank(userLoginReq.getWxCode()))
			return CodeDataResp.valueOfFailed("授权code不能为空");
		UserEntity sysUser=null;
		try {
			
			// 只有一个的情况下不用切换，如有多个小程序才需要切换
//			 if (!wxMaService.switchover(wxMaMiniAppCfg.getAppId())) {
//		            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", wxMaMiniAppCfg.getAppId()));
//		     }

			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(userLoginReq.getWxCode());
			//检查unionid是否存在， 存在则取出记录，从记录中根据appId获取openid ,不存在添加openid并更新，存在则结束
			log.info("微信用户的 unionid:{}", session.getUnionid());
			//根据OpenId获取用户 o0lRD48wC2Nbt4CDCjg9to5xc1tY
			 sysUser =getUserByOpenId(session.getOpenid());

			 if(sysUser == null ) {
				sysUser=new UserEntity();
				sysUser.setUserType(1);
//				sysUser.setNickName(userLoginReq.getNickName());
//				sysUser.setHeadPhoto(userLoginReq.getHeadPhoto());
				sysUser.setOpenId(session.getOpenid());
//				sysUser.setUnionid(session.getUnionid());
				sysUser.setPassword("123456");
				sysUser.setLoginCount(0);
				sysUser.setStatus((byte) 1);
				sysUser.setDeviceId(userLoginReq.getDeviceId());
				sysUser.setRoleType(userLoginReq.getRoleType().byteValue());
				sysUser.setCreateTime(new Date());
				String code = StrUtils.getCode("0","U", new Date());
				sysUser.setCode(code);
				JSONObject param = new JSONObject();
				param.put("code", code);
//				String  returnPath=QRCodeUtil.getQrCodePath(QRCodeTypeEnum.UserQrcode,param);
//				sysUser.setQrCodePath(returnPath);
				if(userLoginReq.getSessionId()!=null) {
					SessionInfoEntity old = this.sessionInfoService.getById(userLoginReq.getSessionId());
					sysUser.setDeviceId(old.getDeviceId());
					sysUser.setDeviceName(old.getDeviceName());
				}
				
				
				super.save(sysUser);
				sysUser.setNickName("微信用户"+sysUser.getId());
				sysUser.setName(sysUser.getNickName());
//				userWalletService.addUserWallet(sysUser.getId());
				this.updateById(sysUser);
				//添加消息通知配置
			}
			if(StringUtils.isNotBlank( userLoginReq.getWxPhoneCode()) ){
				String phone=	getWxUserPhone(wxMaService, userLoginReq.getWxPhoneCode());
				sysUser.setUserPhone(phone);
				this.updateById(sysUser);
			}
			
		} catch (WxErrorException e) {
			log.error(e.getMessage(), e);
//			e.printStackTrace();
			throw e;
		}
		
		if(userLoginReq.getSessionId()!=null && userLoginReq.getSessionId() > 0) 
			aiContextManager.bindUser2Session(sysUser.getId(), sysUser.getNickName(),sysUser.getHeadPhoto(),sysUser.getUserPhone() ,userLoginReq.getSessionId());
		
		LoginReq loginReq = new LoginReq();
		loginReq.setPassword(sysUser.getPassword());
		loginReq.setType(1);//移动端登录
		loginReq.setRoleType(1);//客户登录
		loginReq.setUsername(sysUser.getOpenId());
		loginReq.setPassword(sysUser.getPassword());
		return login(sysUser,loginReq);	
	
	}
	
	@Override
	public String getWxUserPhone(String code) {
		JSONObject param = new JSONObject();
		param.put("code", code);
		String  getUserPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber";
		String result="";
		try {
			result = wxMaService.post(getUserPhoneUrl , param.toJSONString());
			if(StringUtils.isBlank(result) )
				throw new ApiException("请求失败");
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("微信用户的手机号信息:{}", result);
		JSONObject phoneInfo= JSONObject.parseObject(result);
		if(phoneInfo.getInteger("errcode")!=0) 
			throw new ApiException(result);
		 return phoneInfo.getJSONObject("phone_info").getString("purePhoneNumber");
	}

	
	/**
	 * 用户登陆
	 * @param userLoginReq
	 * @return
	 */
	@Override
	public CodeDataResp<UserEntity> login(UserEntity sysUser,LoginReq userLoginReq) {

		if (sysUser == null) {
			throw new ApiException("用户不存在");
		}
		if (!userLoginReq.getPassword().equals(sysUser.getPassword())) {
			throw new ApiException("用户名或密码错误");
		}
		if (!sysUser.getStatus().equals((byte)1) ){
			throw new ApiException("用户被禁用");
		}
		// 初步验证成功
		String token = shiroUserService.userLoginGetToken(userLoginReq,userLoginReq.getType(),
				userLoginReq.getRoleType());
		sysUser.setLoginCount(sysUser.getLoginCount() + 1);
		sysUser.setLastLoginTime(DateUtils.currentSecs().intValue());
		sysUser.setLoginToken(token);
		super.updateById(sysUser);
		

		return CodeDataResp.valueOfSuccess(sysUser);
	}
	
	public String getWxUserPhone(final WxMaService wxMaService,String code) {
		JSONObject param = new JSONObject();
		param.put("code", code);
		String  getUserPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber";
		String result="";
		try {
			result = wxMaService.post(getUserPhoneUrl , param.toJSONString());
			if(StringUtils.isBlank(result) )
				throw new ApiException("请求失败");
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("微信用户的手机号信息:{}", result);
		JSONObject phoneInfo= JSONObject.parseObject(result);
		if(phoneInfo.getInteger("errcode")!=0) 
			throw new ApiException(result);
		 return phoneInfo.getJSONObject("phone_info").getString("purePhoneNumber");
	}


	@Override
	public void refreshUser(String id,String unionid) {
		String key = RedisKeyManager.RootKey+RedisKeyManager.Splitter+"User"+RedisKeyManager.Splitter+id;
		this.redistUtil.removeKey(key);
		key = RedisKeyManager.RootKey+RedisKeyManager.Splitter+"UserUnionid"+RedisKeyManager.Splitter+unionid;
		this.redistUtil.removeKey(key);
		log.info("刷新用户缓存");
		
	}

}
